package com.mall.server.inerceptor;


import com.mall.commons.utils.JwtUtils;

import com.tanhua.model.domain.UmsAdmin;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class  TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            //拦截器有问题,先这么写,回头再改
            String requestURI = request.getRequestURI();
            String[] split = requestURI.split("/");
            for (String s : split) {
                if ("aliyun".equals(s)){
                    throw new Exception();
                }
            }


            //判断token是否有效,没效就返回异常401 ,有效就传入TheradLocal
            String token = request.getHeader("Authorization");
            if (request.getMethod().equals("OPTIONS")) {
                response.setStatus(HttpServletResponse.SC_OK);
                return true;
            }
            token=token.replace("undefined", "");
            log.info(token+"====================================================");


            if (!JwtUtils.verifyToken(token)) {
                response.setStatus(401);
                return false;
            }

            Claims claims = JwtUtils.getClaims(token);
            String username = (String) claims.get("username");
            Integer id = (Integer) claims.get("id");

            UmsAdmin user = new UmsAdmin();
            user.setId(Long.valueOf(id));
            user.setUsername(username);

            UmsAdminHolder.set(user);
            return true;
        } catch (Exception e) {
            return true;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       /* UserHolder.remove();*/
    }
}


